using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Toolbox.DnsService.Interfaces;
using Toolbox.DnsService.Models;

namespace Toolbox.DnsService.Services
{
    /// <summary>
    /// DNS服务配置管理器
    /// 作者：huobing
    /// </summary>
    public class DnsConfigManager : IDnsConfigManager
    {
        private readonly string _configFilePath;
        private DnsServiceConfig _config;
        private bool _disposed = false;

        /// <summary>
        /// 获取配置对象
        /// </summary>
        public DnsServiceConfig Config => _config;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configFilePath">配置文件路径</param>
        public DnsConfigManager(string configFilePath = "Conf/DNSService.conf")
        {
            _configFilePath = configFilePath;
            _config = new DnsServiceConfig();
            
            // 尝试加载现有配置
            LoadConfig();
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <returns>DNS服务配置</returns>
        public DnsServiceConfig LoadConfig()
        {
            try
            {
                if (File.Exists(_configFilePath))
                {
                    var json = File.ReadAllText(_configFilePath);
                    _config = JsonSerializer.Deserialize<DnsServiceConfig>(json) ?? new DnsServiceConfig();
                }
                else
                {
                    // 创建默认配置
                    _config = CreateDefaultConfig();
                    SaveConfig(_config);
                }
            }
            catch (Exception)
            {
                // 创建默认配置
                _config = CreateDefaultConfig();
            }
            
            return _config;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="config">DNS服务配置</param>
        public void SaveConfig(DnsServiceConfig config)
        {
            try
            {
                _config = config;
                var json = JsonSerializer.Serialize(_config, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_configFilePath, json);
            }
            catch (Exception)
            {
                // 保存失败，忽略异常
            }
        }

        /// <summary>
        /// 获取设置值
        /// </summary>
        /// <param name="key">设置键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>设置值</returns>
        public string GetSetting(string key, string defaultValue = "")
        {
            // 暂时返回默认值，后续可以扩展为从配置文件中读取特定设置
            return defaultValue;
        }

        /// <summary>
        /// 保存设置值
        /// </summary>
        /// <param name="key">设置键</param>
        /// <param name="value">设置值</param>
        public void SaveSetting(string key, string value)
        {
            // 暂时不实现，后续可以扩展为保存到配置文件中的特定设置
        }

        /// <summary>
        /// 获取本地DNS服务端口
        /// </summary>
        /// <returns>端口号</returns>
        public int GetLocalDnsPort()
        {
            return _config.Port;
        }

        /// <summary>
        /// 设置本地DNS服务端口
        /// </summary>
        /// <param name="port">端口号</param>
        /// <returns>是否设置成功</returns>
        public bool SetLocalDnsPort(int port)
        {
            if (port < 1 || port > 65535)
                return false;

            _config.Port = port;
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 获取上游DNS服务器列表
        /// </summary>
        /// <returns>DNS服务器列表</returns>
        public List<string> GetUpstreamDnsServers()
        {
            return _config.UpstreamDnsServers ?? new List<string>();
        }

        /// <summary>
        /// 添加上游DNS服务器
        /// </summary>
        /// <param name="dnsServer">DNS服务器地址</param>
        /// <returns>是否添加成功</returns>
        public bool AddUpstreamDnsServer(string dnsServer)
        {
            if (string.IsNullOrWhiteSpace(dnsServer))
                return false;

            _config.UpstreamDnsServers ??= new List<string>();
            
            if (!_config.UpstreamDnsServers.Contains(dnsServer))
            {
                _config.UpstreamDnsServers.Add(dnsServer);
                SaveConfig(_config);
                return true;
            }
            
            return true;
        }

        /// <summary>
        /// 移除上游DNS服务器
        /// </summary>
        /// <param name="dnsServer">DNS服务器地址</param>
        /// <returns>是否移除成功</returns>
        public bool RemoveUpstreamDnsServer(string dnsServer)
        {
            if (string.IsNullOrWhiteSpace(dnsServer) || _config.UpstreamDnsServers == null)
                return false;

            var removed = _config.UpstreamDnsServers.Remove(dnsServer);
            if (removed)
            {
                SaveConfig(_config);
                return true;
            }
            
            return false;
        }

        /// <summary>
        /// 获取DNS记录字典
        /// </summary>
        /// <returns>DNS记录字典</returns>
        public Dictionary<string, string> GetDnsRecords()
        {
            return _config.DnsRecords ?? new Dictionary<string, string>();
        }

        /// <summary>
        /// 添加DNS记录
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="ip">IP地址</param>
        /// <returns>是否添加成功</returns>
        public bool AddDnsRecord(string domain, string ip)
        {
            if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(ip))
                return false;

            _config.DnsRecords ??= new Dictionary<string, string>();
            
            // 直接添加或更新记录
            _config.DnsRecords[domain] = ip;
            
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 移除DNS记录
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>是否移除成功</returns>
        public bool RemoveDnsRecord(string domain)
        {
            if (string.IsNullOrWhiteSpace(domain) || _config.DnsRecords == null)
                return false;

            var removed = _config.DnsRecords.Remove(domain);
            if (removed)
            {
                SaveConfig(_config);
                return true;
            }
            
            return false;
        }

        /// <summary>
        /// 获取是否启用DNS缓存
        /// </summary>
        /// <returns>是否启用缓存</returns>
        public bool GetEnableCache()
        {
            return _config.CacheExpirationMinutes > 0;
        }

        /// <summary>
        /// 设置是否启用DNS缓存
        /// </summary>
        /// <param name="enable">是否启用</param>
        /// <returns>是否设置成功</returns>
        public bool SetEnableCache(bool enable)
        {
            _config.CacheExpirationMinutes = enable ? 60 : 0;
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 获取缓存过期时间（分钟）
        /// </summary>
        /// <returns>缓存过期时间</returns>
        public int GetCacheExpirationMinutes()
        {
            return _config.CacheExpirationMinutes;
        }

        /// <summary>
        /// 设置缓存过期时间（分钟）
        /// </summary>
        /// <param name="minutes">过期时间</param>
        /// <returns>是否设置成功</returns>
        public bool SetCacheExpirationMinutes(int minutes)
        {
            if (minutes < 1)
                return false;

            _config.CacheExpirationMinutes = minutes;
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 获取是否启用自动启动
        /// </summary>
        /// <returns>是否启用自动启动</returns>
        public bool GetAutoStart()
        {
            return _config.AutoStart;
        }

        /// <summary>
        /// 设置是否启用自动启动
        /// </summary>
        /// <param name="autoStart">是否启用</param>
        /// <returns>是否设置成功</returns>
        public bool SetAutoStart(bool autoStart)
        {
            _config.AutoStart = autoStart;
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 获取是否启用日志记录
        /// </summary>
        /// <returns>是否启用日志记录</returns>
        public bool GetEnableLogging()
        {
            return _config.EnableLogging;
        }

        /// <summary>
        /// 设置是否启用日志记录
        /// </summary>
        /// <param name="enable">是否启用</param>
        /// <returns>是否设置成功</returns>
        public bool SetEnableLogging(bool enable)
        {
            _config.EnableLogging = enable;
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 重置为默认配置
        /// </summary>
        /// <returns>是否重置成功</returns>
        public bool ResetToDefaults()
        {
            _config = CreateDefaultConfig();
            SaveConfig(_config);
            return true;
        }

        /// <summary>
        /// 创建默认配置
        /// </summary>
        /// <returns>默认配置对象</returns>
        private DnsServiceConfig CreateDefaultConfig()
        {
            return new DnsServiceConfig
            {
                Port = 153,
                UpstreamDnsServers = new List<string> { "8.8.8.8", "114.114.114.114" },
                DnsCache = new Dictionary<string, string>(),
                CacheExpirationMinutes = 60,
                AutoStart = false,
                EnableLogging = true
            };
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing">是否释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // 保存配置
                    SaveConfig(_config);
                }
                
                _disposed = true;
            }
        }
    }
}